package com.fjwt.gz.task.offfline;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.entity.AwardCouponEntity;
import com.fjwt.gz.service.impl.AwardCouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 卡券奖品过期
 */
@Slf4j
@Component
public class AwardCouponOffLineTask {

    @Autowired
    private AwardCouponService awardCouponService;
    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

//    @Scheduled(cron = "${cron.AwardCouponOffLineTask}")//每3秒执行一次
    @Transactional
    public void start() {
        log.info("开始进入卡券奖品过期定时任务，下线已过期的卡券奖品，开始时间:{}", DateUtil.now());

        //查询条件：状态 不等于3：未过期 & 过期时间小于当前时间
        LambdaQueryWrapper<AwardCouponEntity> gw =
                AwardCouponEntity.gw()
                        .in(AwardCouponEntity::getState, Constants.AWARD_STATE.OFFLINE, Constants.AWARD_STATE.ONLINE)
                        .lt(AwardCouponEntity::getEndTime, new Date());
        List<AwardCouponEntity> updateList = new ArrayList<>();
        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<AwardCouponEntity> awardCouponEntityIPage = awardCouponService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), gw);
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(awardCouponEntityIPage));

                if (awardCouponEntityIPage == null || awardCouponEntityIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }

                for (AwardCouponEntity awardCouponEntity : awardCouponEntityIPage.getRecords()) {
                    log.info("此时处理的数据的是：{}", JSONUtil.toJsonStr(awardCouponEntity));
                    awardCouponEntity.setState(Constants.AWARD_STATE.EXPIRED);
                    awardCouponEntity.setUpdatedAt(new Date());
                    updateList.add(awardCouponEntity);
                    currentPageIndex++;
                }
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        if (ObjectUtils.isNotEmpty(updateList)){
            awardCouponService.updateBatchById(updateList);
        }
        log.info("结束卡券奖品过期定时任务，下线已过期的卡券奖品，结束时间:{}", DateUtil.now());
    }
}
